using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Text.Json;

namespace DesktopWidgetApp.UI.Helpers
{
    /// <summary>
    /// 样式管理器
    /// 负责管理应用程序的外观样式和用户自定义设置
    /// </summary>
    public class StyleManager
    {
        private const string StyleSettingsFileName = "style_settings.json";
        private readonly string _settingsFilePath;
        private StyleSettings _currentSettings;

        /// <summary>
        /// 当前样式设置
        /// </summary>
        public StyleSettings CurrentSettings => _currentSettings;

        /// <summary>
        /// 样式变更事件
        /// </summary>
        public static event EventHandler StyleChanged;

        /// <summary>
        /// 触发样式变更事件
        /// </summary>
        private static void OnStyleChanged()
        {
            StyleChanged?.Invoke(null, EventArgs.Empty);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public StyleManager()
        {
            // 设置样式设置文件路径
            var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var appFolder = Path.Combine(appDataPath, "DesktopWidgetApp");
            if (!Directory.Exists(appFolder))
            {
                Directory.CreateDirectory(appFolder);
            }
            _settingsFilePath = Path.Combine(appFolder, StyleSettingsFileName);

            // 加载样式设置
            LoadStyleSettings();
        }

        /// <summary>
        /// 加载样式设置
        /// </summary>
        private void LoadStyleSettings()
        {
            try
            {
                if (File.Exists(_settingsFilePath))
                {
                    var json = File.ReadAllText(_settingsFilePath);
                    _currentSettings = JsonSerializer.Deserialize<StyleSettings>(json);
                }
                else
                {
                    // 使用默认设置
                    _currentSettings = GetDefaultSettings();
                    SaveStyleSettings();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("加载样式设置失败: " + ex.Message);
                _currentSettings = GetDefaultSettings();
            }
        }

        /// <summary>
        /// 保存样式设置
        /// </summary>
        public void SaveStyleSettings()
        {
            try
            {
                var json = JsonSerializer.Serialize(_currentSettings, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(_settingsFilePath, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine("保存样式设置失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 获取默认样式设置
        /// </summary>
        private StyleSettings GetDefaultSettings()
        {
            return new StyleSettings
            {
                BackgroundColor = "#F0F0F0",
                BorderColor = "#CCCCCC",
                TitleBarColor = "#E0E0E0",
                TitleTextColor = "#000000",
                ContentBackgroundColor = "#FFFFFF",
                ContentTextColor = "#000000",
                ButtonBackgroundColor = "#E0E0E0",
                ButtonTextColor = "#000000",
                CornerRadius = 10,
                ShadowEnabled = true,
                FontSize = 14,
                FontFamily = "Microsoft YaHei"
            };
        }

        /// <summary>
        /// 应用样式到窗口
        /// </summary>
        /// <param name="window">要应用样式的窗口</param>
        public void ApplyStyleToWindow(Window window)
        {
            ApplyStyleToWindow(window, _currentSettings);
        }

        /// <summary>
        /// 应用样式到窗口
        /// </summary>
        /// <param name="window">要应用样式的窗口</param>
        /// <param name="settings">样式设置</param>
        public void ApplyStyleToWindow(Window window, StyleSettings settings)
        {
            if (window == null || settings == null)
                return;

            try
            {
                // 先清除现有的样式资源字典
                for (int i = window.Resources.MergedDictionaries.Count - 1; i >= 0; i--)
                {
                    var dict = window.Resources.MergedDictionaries[i];
                    if (dict.Contains("BackgroundColor"))
                    {
                        window.Resources.MergedDictionaries.Remove(dict);
                    }
                }

                // 创建一个新的资源字典
                var resourceDictionary = new ResourceDictionary();

                // 设置颜色资源
                resourceDictionary.Add("BackgroundColor", (Color)ColorConverter.ConvertFromString(settings.BackgroundColor));
                resourceDictionary.Add("BorderColor", (Color)ColorConverter.ConvertFromString(settings.BorderColor));
                resourceDictionary.Add("TitleBarColor", (Color)ColorConverter.ConvertFromString(settings.TitleBarColor));
                resourceDictionary.Add("TitleTextColor", (Color)ColorConverter.ConvertFromString(settings.TitleTextColor));
                resourceDictionary.Add("ContentBackgroundColor", (Color)ColorConverter.ConvertFromString(settings.ContentBackgroundColor));
                resourceDictionary.Add("ContentTextColor", (Color)ColorConverter.ConvertFromString(settings.ContentTextColor));
                resourceDictionary.Add("ButtonBackgroundColor", (Color)ColorConverter.ConvertFromString(settings.ButtonBackgroundColor));
                resourceDictionary.Add("ButtonTextColor", (Color)ColorConverter.ConvertFromString(settings.ButtonTextColor));

                // 设置其他样式资源
                resourceDictionary.Add("CornerRadius", new CornerRadius(settings.CornerRadius));
                resourceDictionary.Add("FontSize", settings.FontSize);
                resourceDictionary.Add("FontFamily", new FontFamily(settings.FontFamily));
                resourceDictionary.Add("ShadowEnabled", settings.ShadowEnabled);

                // 应用到窗口的资源中
                window.Resources.MergedDictionaries.Add(resourceDictionary);
            }
            catch (Exception ex)
            {
                Console.WriteLine("应用样式失败: " + ex.Message);
            }
        }

        /// <summary>
        /// 获取当前样式设置
        /// </summary>
        /// <returns>当前样式设置</returns>
        public static StyleSettings GetCurrentStyleSettings()
        {
            var manager = new StyleManager();
            return manager._currentSettings;
        }

        /// <summary>
        /// 更新样式设置
        /// </summary>
        /// <param name="settings">新的样式设置</param>
        public void UpdateStyleSettings(StyleSettings settings)
        {
            _currentSettings = settings;
            SaveStyleSettings();
            
            // 触发样式变更事件
            OnStyleChanged();
        }

        /// <summary>
        /// 重置为默认样式
        /// </summary>
        public void ResetToDefaultStyle()
        {
            _currentSettings = GetDefaultSettings();
            SaveStyleSettings();
        }
    }

    /// <summary>
    /// 样式设置类
    /// 存储用户自定义的样式配置
    /// </summary>
    public class StyleSettings
    {
        public string BackgroundColor { get; set; }
        public string BorderColor { get; set; }
        public string TitleBarColor { get; set; }
        public string TitleTextColor { get; set; }
        public string ContentBackgroundColor { get; set; }
        public string ContentTextColor { get; set; }
        public string ButtonBackgroundColor { get; set; }
        public string ButtonTextColor { get; set; }
        public double CornerRadius { get; set; }
        public bool ShadowEnabled { get; set; }
        public double FontSize { get; set; }
        public string FontFamily { get; set; }
    }
}